#include <iterator>
#include <iostream>
#include <sstream>
#include <algorithm>
#include "tree_tagger.h++"
#include "file_reader.h++"
#include "searcher.h++"
#include "word_tree.h++"
#include "word_filter.h++"

struct LemmaGetter {
	std::vector<Word> words;
	Searcher::vector_group_type groups;
	int pending_group_index;
	void found_word(const UnserializedDocument&, const Word& word) {
		words.push_back(word);
	}
	void ignoring_word(const Word& word) {
		if (word.category == "PUN:cit") {
			if (pending_group_index < 0) {
				pending_group_index = words.size();
			} else {
				Searcher::group_type grp(pending_group_index,
						words.size());
				groups.push_back(grp);
				pending_group_index = -1;
			}
			return;
		}
		words.push_back(word);
		words.back().lemma = "";
	}
	void read_this(std::istream& stream) {
		UnserializedDocument fake("fake");
		TreeTaggerFileReader ttfile_reader;
		WordFilter::Proxy<LemmaGetter> filter(*this);
		ttfile_reader.read_stream(stream, fake, filter);
	}
	LemmaGetter() : words(), groups(), pending_group_index(-1) {}
} lemma_getter;

int main(int argc, char* argv[]) {
	if (argc < 2) {
		std::cerr << "usage :\n\t"
			<< argv[0] << " path/to/index/"/* path/to/corpus*/" query"
			<< std::endl;
		return 2;
	}
	std::ostringstream os;
	std::copy(&argv[2], &argv[argc],
			std::ostream_iterator<char*>(os, " "));
	TreeTagger tt;
	LemmaGetter lemma_getter;
	try {
		tt.start_treetagger(os.str());
		lemma_getter.read_this(tt.get_stream());

		tt.wait_and_close();
		if (lemma_getter.words.empty()) {
			throw TreeTagger::DoesntWorkException(
						"no treetagger output");
		}
	} catch (TreeTagger::DoesntWorkException& e) {
		std::cerr << "(maybe you can try setting the "TREETAGGER_ENVVAR
			" environement variable to a path to tree-tagger-lang)"
			<< std::endl;
		return 2;
	}

	boost::filesystem::path indexdir(argv[1]);
//	boost::filesystem::path corpuspath(argv[2]);
	ReadOnlyMappedMemory tree((indexdir/"TRIE.INDEX").c_str());
	ReadOnlyMappedMemory infofile((indexdir/"INFO.INDEX").c_str());
	ReadOnlyMappedMemory postingfile((indexdir/"POSTINGS.INDEX").c_str());
	Searcher searcher;
	searcher.set_wordtree_file(&tree);
	searcher.set_moreinfo_file(&infofile);
	searcher.set_documents_file(&infofile);
	searcher.set_paths_file(&infofile);
	searcher.set_postings_file(&postingfile);
	//searcher

	size_t nb_results = 20;

	Searcher::doc_score_vector_type result(
		searcher.search(lemma_getter.words, lemma_getter.groups, nb_results));


	std::cout << "Found " << nb_results << " matching documents." << std::endl;

	BOOST_FOREACH(Searcher::doc_score_pair& doc_score, result) {
		std::cout
			<< infofile.get(doc_score.first).get_path_string(
						infofile) <<
			" (score:"<<doc_score.second*100<<"%)" << std::endl;


	}
	
	return 0;
}
